package com.example.xunai.service.ai.impl;

import com.example.xunai.dto.request.ai.ChatRequest;
import com.example.xunai.service.ai.BatchChatService;
import com.example.xunai.service.ai.SyncChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class BatchChatServiceImpl implements BatchChatService {

    private final SyncChatService syncChatService;

    @Override
    public List<String> batchChat(List<ChatRequest> requests) {
        log.info("BatchChatService - 批量聊天请求，数量: {}", requests.size());

        List<String> responses = new ArrayList<>();
        for (ChatRequest request : requests) {
            try {
                String response = syncChatService.getAiResponse(request);
                responses.add(response);
            } catch (Exception e) {
                log.error("批量聊天请求处理失败: {}", request.toLogString(), e);
                responses.add("处理失败: " + e.getMessage());
            }
        }

        return responses;
    }

    @Override
    public void batchChatAsync(List<ChatRequest> requests, BatchChatCallback callback) {
        log.info("BatchChatService - 异步批量聊天请求，数量: {}", requests.size());

        // 可以使用线程池异步处理
        new Thread(() -> {
            for (int i = 0; i < requests.size(); i++) {
                ChatRequest request = requests.get(i);
                try {
                    String response = syncChatService.getAiResponse(request);
                    if (callback != null) {
                        callback.onSuccess(i, request, response);
                    }
                } catch (Exception e) {
                    log.error("批量聊天请求处理失败: {}", request.toLogString(), e);
                    if (callback != null) {
                        callback.onError(i, request, e);
                    }
                }
            }

            if (callback != null) {
                callback.onComplete();
            }
        }).start();
    }
}